package com.yunding.util;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author Sun
 * @date 2020-07-30 18:39
 */

public class FtpUploadFile {

    /**
     * FTP IP
     */
    private static final String HOSTNAME = "39.97.181.150" ;

    /**
     * FTP 端口号
     */
    private static final int PORT = 21;

    /**
     * FTP 登录账号
     */
    private static final String USERNAME = "ftpuser";

    /**
     * FTP 登录密码
     */
    private static final String PASSWORD = "ftpuser";

    /**
     * FTP 工作路径
     */
    private static final String PATHNAME = "/home/ftpuser/www/images";


    /**
     * 上传文件（可供Action/Controller层使用）
     * @param fileName 上传到 FTP 服务器后的文件名称
     * @param inputStream 输入文件流
     */
    public static void uploadFile(String fileName, FileInputStream inputStream){
        FTPClient ftpClient = new FTPClient();
        //设置超时
        ftpClient.setConnectTimeout(60 * 60 * 1000 * 6);
        //设置编码
        ftpClient.setControlEncoding("UTF-8");
        try {
            //连接FTP服务器
            ftpClient.connect(HOSTNAME, PORT);
            //登录FTP服务器
            ftpClient.login(USERNAME, PASSWORD);
            //是否成功登录FTP服务器
            int replyCode = ftpClient.getReplyCode();
            if(!FTPReply.isPositiveCompletion(replyCode)){
                return;
            }
            System.out.println("===========登录FTP成功了==========");
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            //切换路径 创建路径
            ftpClient.makeDirectory(PATHNAME);
            ftpClient.changeWorkingDirectory(PATHNAME);
            ftpClient.enterLocalPassiveMode();
            //设置缓冲
            ftpClient.setBufferSize(1024 * 1024 * 20);
            //保持连接
            ftpClient.setKeepAlive(true);
            boolean a = ftpClient.storeFile(new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8), inputStream);
            if(a){
                System.out.println("===========创建文件成功=============="+ true);
                boolean status = ftpClient.rename(fileName, fileName);
                if(status){
                    System.out.println("===========修改文件名称成功=============="+ true);
                }
            }
            inputStream.close();
            ftpClient.logout();
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            if(ftpClient.isConnected()){
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
